package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户密码认证方式
 * @author Mdd
 * @Github <a href="https://github.com/mdd123cc"/>
 * @Gitee <a href="https://gitee.com/mdd115192"/>
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    XcUserMapper xcUserMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Resource
    CheckCodeClient checkCodeClient;
    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //=============================校验验证码====================================
        String checkcodekey = authParamsDto.getCheckcodekey();
        String checkcode = authParamsDto.getCheckcode();
        if (StringUtils.isEmpty(checkcodekey)||StringUtils.isEmpty(checkcode)){
            throw new RuntimeException("请输入验证码!");
        }
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if (!verify){
            //校验失败
            throw new RuntimeException("验证码错误!");
        }
        //=============================校验用户名密码====================================
        //查询用户信息
        //获得用户名
        String username = authParamsDto.getUsername();
        //根据username查询用户信息
        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XcUser::getUsername,username);
        XcUser user = xcUserMapper.selectOne(queryWrapper);
        //为null说明用户不存在
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        //获取用户正确的密码
        String password = user.getPassword();
        //验证密码是否正确
        boolean matches = passwordEncoder.matches(authParamsDto.getPassword(),password );
        if (!matches) {
            throw new RuntimeException("账户或密码错误!");
        }
        // todo 查询该用户权限列表
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(user,xcUserExt);
        return xcUserExt;
    }
}
